package idx

import "io"

type IdxItem struct {
	idx    *Idx
	offset int64
	prev   *IdxItem
	next   *IdxItem
}

type IdxList struct {
	head *IdxItem
	curr *IdxItem
	last *IdxItem
}

func (l *IdxList) Insert(item *IdxItem) {
	if l.head == nil {
		l.head = item
		l.last = item
	} else {
		l.last.next = item
		item.prev = l.last
		l.last = item
	}
}

func (l *IdxList) Remove(item *IdxItem) {
	//双向列表删除
	if item.prev == nil && item.next == nil {
		l.head = nil
		l.last = nil
		return
	}
	if item.prev == nil {
		item.next.prev = nil
		l.head = item.next
	} else if item.next == nil {
		item.prev.next = nil
		l.last = item.prev
	} else {
		item.prev.next = item.next
		item.next.prev = item.prev
	}
}

func (l *IdxList) Next() (*IdxItem, error) {
	if l.curr == nil {
		if l.head == nil {
			return nil, io.EOF
		}
		l.curr = l.head
		return l.curr, nil
	}
	if l.curr.next == nil {
		return nil, io.EOF
	}
	l.curr = l.curr.next
	return l.curr, nil
}
